<template>
    <div class="app-container tz-app" style="overflow-y:hidden">


        <div class="zt-select flex-s">

            <div class="flex-left flex-item fry-box">
                <el-select v-model="queryParams.locatedAddress" filterable placeholder="所属地"
                    class="zt-input-min rihgt-m5" style="width: 140px;font-weight: 600;">
                    <el-option v-for="item in  dict.type.located_address" :key="item.value" :label="item.label"
                        :value="item.value" />
                </el-select>
                <el-select v-model="queryParams.radio" placeholder="选择电台" class="blank-input m-10" @change="radioChange"
                    style="width:200px;">
                    <el-option v-for="item in listAll.station" :key="item.radioStationCode"
                        :label="item.radioStationName" :value="item.radioStationCode">
                    </el-option>
                </el-select>
                <div class="flex-item overall-set" @click="getParameter">
                    <img src="@/assets/images/stz.png" style="cursor: pointer;" />全频谱数据设置
                </div>

                <button class="bt-yellow" @click="postFfbStart()" v-show="!beFrequency && queryParams.radio != null">开始</button>
                <button class="bt-yellow" @click="postFfbStop()" v-show="beFrequency">停止</button>

                <div class="zt-data flex-item">
                    <div>{{ formatTime }}</div>
                </div>
            </div>
        </div>


        <div class="frequency-message">

            <div class="frequency-message-main">
                <div class="headline-text">
                    <div class="h-text">射频直采数据</div>
                    <div class="h-button">
                        <div class="h-num flex">
                            <!-- {{ frequencyNum }}  -->
                            <input class="h-num-input" type="number" v-model="frequencyNum" @blur="calculateWire" />MHz
                        </div>


                        <div :class="!beFrequency ? 'h-btn-n' : 'h-btn'" @click="belowAddPopUpData">下变频数据</div>
                    </div>
                </div>

                <div class="container" @click="showLineWay($event)">
                    <!-- <div class="line" v-if="showLine" :style="{ left: linePosition + 'px' }"></div> -->
                    <!-- <p>原始数据: {{ input_data.data }}</p>
                    <p>扩展后的数据: {{ expanded_data }}</p> -->
                    <!-- <frequency></frequency> -->
                    <frequency style="width: 100%;" :inputData="frequencyData" height="550px" @setNumber="setNumber"
                        :frequencyNum="frequencyNumInput" :type="1">
                        <!-- <frequency style="width: 100%;" :xAxisData="xAxisData" :seriesData="seriesData" height="500px"> -->
                    </frequency>
                    <Heating style="width: 100%;" height="100px" :inputData="frequencyData"></Heating>
                    <!-- <Heating></Heating> -->
                </div>

            </div>

            <div class="frequency-message-minor" ref="componentContainer">
                <div style="height: 100%;">
                    <div class="frequency-headline">基础设置</div>
                    <data-set :inputData="popUpData[0].frequencyData" v-if="popUpData[0]" :id="popUpData[0].id"
                        @play="playStart" @go="go" :type="2">
                    </data-set>
                </div>
            </div>

        </div>

        <div v-for="(item, index) in popUpData" :key="index" v-show="index != 0">
            <PopUp class="frequency-pop" :inputData="item.frequencyData" @closeDialog="closeDialogPopUp">
                <template v-slot:default>
                    <data-set :inputData="item.frequencyData" @play="playStart" @go="go" :id="item.id"> </data-set>
                </template>
            </PopUp>
        </div>


        <min-dialog :title="frequencySet.title" width="450px" :visible="frequencySet.open"
            @closeDialog="cancelFrequencySet">
            <template v-slot:default>
                <div class="min-dialog" style="height: 250px;padding: 10px;margin-top: 40px;">

                    <!-- <el-form :model="frequencySet.data" label-width="100px">
                        <el-form-item label="起始频率:">
                            <div class="flex">
                                <el-input class="zt-input-80" v-model="frequencySet.data.frequencyStart" placeholder="起始"
                                    style="width: 80px;"></el-input>
                                <div style="margin: 0 12px 0 15px; font-size: 14px; color: #9A9DAA;">结束频率:</div>
                                <el-input class="zt-input-80" v-model="frequencySet.data.frequencyEnd" placeholder="结束"
                                    style="width: 80px;"></el-input>
                            </div>

                        </el-form-item>
                    </el-form> -->

                    <el-form :model="frequencySet" label-width="120px">
                        <el-form-item label="采集宽带设置:">
                            <el-input class="zt-input" v-model="frequencySet.data[0].configValue" placeholder="采集宽带设置"
                                style="width: 250px;"></el-input>
                            MHZ
                        </el-form-item>
                        <el-form-item label="中心频率设置:">
                            <el-input class="zt-input" v-model="frequencySet.data[1].configValue" placeholder="中心频率设置"
                                style="width: 250px;"></el-input>
                            MHZ
                        </el-form-item>
                    </el-form>
                    <el-button class="bt-blue" style="margin-left: 250px;margin-top: 50px;"
                        @click="postParameter">确认</el-button>
                </div>
            </template>
        </min-dialog>

    </div>
</template>

<script>




import { ffbStop, ffbStart, channelStart, channelStop, playStart, playStop, recordStart, recordStop, sdrSet, queryParameter, editParameter } from "@/api/business/frequency";
import PopUp from "@/components/TZ/PopUp"
import PopUp2 from "@/components/TZ/PopUp2"
import PopUp3 from "@/components/TZ/PopUp3"
import Frequency from "@/components/TZ/Frequency"
import Heating from "@/components/TZ/Heating"
import DataSet from "@/components/TZ/DataSet"
import MinDialog from "@/components/TZ/MinDialog"
import { v4 as uuidv4 } from 'uuid';
import Decimal from 'decimal.js';
import { getRadioStationList } from "@/api/business/station";
import { base64PlayUrl } from "@/utils/transcoding"

export default {
    components: { PopUp, Frequency, Heating, DataSet, MinDialog, PopUp2, PopUp3 },
    dicts: ['located_address'],
    name: "Room",
    data() {
        return {
            // 当前开启的频谱
            startObj: null,
            showLine: false,
            linePosition: 0,
            audio: '',
            // websiteUrl: 'https://open.ys7.com/jssdk/theme.html?url=ezopen://open.ys7.com/AB7723774/1.hd.live&accessToken=ar.51nh8qcdar7f092r3v558s4e5qvno5hg-2vehii7agm-16f45n0-tvdypacou&id=ysopen',
            // audio: '',
            audioContext: new (window.AudioContext || window.webkitAudioContext)(), // 创建AudioContext
            radioNum: 0,
            xAxisData: [],
            seriesData: [],
            popUpData: [
                {
                    id: "888",
                    frequencyData: null,
                    central: null,
                }
            ], // 保存组件数据的数组
            dynamicComponent: null, // 动态组件的名称
            queryParams: {
                locatedAddress: null,
                name: null,
                radio: null,
            },
            radioCode: null,
            wsArr: [
            ],
            frequencyData: {
                // central: 6500,
                // need_points: 512,
                // points: 512,
                // data: "-15, -18, -19, -19, -15, -18, -23, -25, -16, -18, -18, -21, -17, -19, -26, -21, -20, -24, -16, -16, -21, -17, -20, -23, -18, -17, -16, -17, -19, -16, -16, -22, -16, -17, -19, -23, -23, -17, -20, -20, -19, -17, -19, -19, -19, -26, -18, -25, -16, -20, -19, -19, -27, -15, -20, -17, -16, -19, -14, -28, -17, -16, -20, -23, -19, -18, -18, -23, -14, -17, -16, -17, -18, -15, -15, -20, -23, -19, -16, -20, -20, -20, -16, -19, -18, -26, -27, -19, -17, -19, -17, -17, -18, -17, -20, -19, -18, -23, -17, -22, -17, -17, -18, -17, -17, -19, -16, -20, -17, -19, -15, -23, -20, -22, -18, -16, -17, -20, -17, -25, -21, -17, -17, -20, -17, -24, -19, -17, -16, -17, -22, -18, -20, -18, -14, -18, -22, -28, -14, -20, -16, -18, -16, -17, -16, -15, -17, -15, -20, -17, -22, -17, -17, -18, -18, -15, -18, -16, -20, -20, -16, -18, -17, -19, -16, -19, -15, -17, -19, -19, -16, -21, -21, -18, -21, -16, -14, -19, -19, -18, -19, -19, -16, -16, -19, -16, -16, -17, -16, -16, -17, -14, -17, -18, -17, -14, -21, -18, -17, -14, -18, -16, -20, -17, -15, -16, -19, -15, -16, -15, -20, -18, -20, -15, -14, -24, -17, -17, -19, -17, -19, -21, -19, -20, -17, -16, -22, -17, -22, -18, -16, -23, -22, -20, -22, -27, -22, -25, -28, -25, -28, -28, -29, -27, -31, -28, -29, -30, -30, -31, -26, -28, -32, -26, -24, -30, -27, -24, -28, -28, -23, -27, -25, -27, -27, -27, -25, -27, -28, -28, -28, -27, -26, -25, -28, -24, -21, -25, -23, -19, -18, -20, -23, -15, -18, -18, -20, -32, -18, -20, -23, -15, -14, -19, -13, -17, -17, -18, -20, -20, -15, -14, -16, -14, -14, -13, -16, -14, -19, -14, -14, -16, -17, -15, -17, -17, -14, -15, -14, -15, -16, -16, -16, -16, -19, -19, -20, -19, -24, -17, -23, -14, -15, -20, -19, -18, -16, -21, -20, -18, -15, -13, -15, -13, -22, -19, -19, -16, -16, -19, -20, -17, -20, -16, -25, -22, -17, -19, -17, -23, -21, -19, -16, -15, -16, -18, -19, -14, -17, -14, -17, -17, -14, -16, -15, -26, -16, -17, -19, -20, -13, -16, -16, -18, -14, -16, -23, -16, -19, -21, -24, -15, -17, -21, -16, -18, -14, -15, -18, -16, -21, -15, -23, -14, -25, -15, -14, -13, -17, -16, -21, -17, -18, -18, -21, -14, -24, -20, -17, -15, -15, -20, -16, -19, -22, -16, -15, -13, -17, -18, -18, -17, -25, -18, -17, -17, -21, -18, -19, -25, -19, -16, -14, -26, -17, -17, -18, -18, -21, -20, -19, -18, -14, -21, -21, -25, -17, -16, -17, -17, -19, -17, -18, -19, -19, -20, -22, -23, -18, -17, -18, -17, -19, -21, -16, -22, -15, -25, -17, -21, -20, -17, -18, -21, -19, -21, -18, -17, -17, -18, -16, -22, -27, -19, -16, -18, -16, -18, -17, -15, -22, -22, -25, -21, -22, -20, -20, -21, -21, -18, -18, -20",
                central: 0,
                need_points: 0,
                bandwidth: 0,
                points: 0,
                data: "",
            },
            frequencyDataMin: {
                central: 0,
                need_points: 0,
                bandwidth: 0,
                points: 0,
                data: "",
            },
            frequencyNum: 0,
            ws: null,
            // url: "ws://192.168.1.18:9208/websocket",
            url: "ws://140.210.217.137:9208/websocket",
            frequencySet: {
                title: "全频率设置",
                open: false,
                data: [
                    {
                        "createBy": "admin",
                        "createTime": "2024-01-26 09:30:35",
                        "updateBy": "admin",
                        "updateTime": "2024-01-26 09:34:27",
                        "remark": null,
                        "configId": 100,
                        "configName": "采集带宽",
                        "configKey": "business.collect.bandwidth",
                        "configValue": "2",
                        "configType": "Y"
                    },
                    {
                        "createBy": "admin",
                        "createTime": "2024-01-26 09:30:54",
                        "updateBy": "admin",
                        "updateTime": "2024-01-26 09:34:11",
                        "remark": null,
                        "configId": 101,
                        "configName": "中心频率",
                        "configKey": "business.center.frequency",
                        "configValue": "2",
                        "configType": "Y"
                    }
                ]
            },
            uuid: this.generateUUIDWithoutHyphens(),
            listAll: {
                station: [],
            },
            beFrequency: false,//是否有主频率信息
            audioElement: null,//音频播放
            audioPlay: false,
            base64String: '',
            base64Arry: [],
            // this.audioElement.src = url;
            audioUrls: [],
            audioContext: null,
            audioBufferSources: [],
            currentBufferSource: null,
            currentAudioUrl: null,
            playing: false,
            playCentral: null,//当前播放的中心频谱
            now: new Date(),
            //音频时长
            audioBufferQueue: [], // 音频数据缓冲队列
            bufferTimer: null, // 定时器
            audioUrl: '', // 音频URL
            audioDuration: null, // 音频时长，初始值为null
            heartbeatInterval: null,//心跳
            start: {
            },
            central: 4500,//全频道
            bandwidth: 2,//带宽
            unit: {//单位
                central: 1000,//全频道
                bandwidth: 1000000,//带宽
                bandwidthGo: 1000,
            },
            timerActive: false,
            seconds: 0,
            frequencyNumInput: '0',
            bandwidthAdd: 400,//下变频增加的带宽大小


        }
    },
    // 在Vue组件的destroyed生命周期钩子中清除定时器
    destroyed() {
        clearInterval(this.heartbeatInterval);
    },
    created() {

    },
    mounted() {
        // 在组件挂载后启动定时器
        // this.startTimer();
        this.getListAll()
        this.join()
        this.audioElement = new Audio();
        // this.getData()
        // this.audio = base64PlayUrl(a);
    },
    beforeDestroy() {
        // this.ws.close();
        this.clostJoin();
        // 在组件销毁前清除定时器，防止内存泄漏
        // clearInterval(this.timerInterval);

    },
    computed: {
        formatTime() {
            const hours = Math.floor(this.seconds / 3600);
            const minutes = Math.floor((this.seconds % 3600) / 60);
            const seconds = this.seconds % 60;
            return `${this.pad(hours)}:${this.pad(minutes)}:${this.pad(seconds)}`;
        }
    },
    methods: {
        calculateWire() {//失去聚焦计算刻度线位置
            this.frequencyNumInput = this.frequencyNum + ''
        },
        pad(value) {
            return value < 10 ? '0' + value : value;
        },
        startTimers() {
            this.timerActive = true;
            this.timer = setInterval(() => {
                console.log(this.seconds);
                this.seconds++;
            }, 1000);
        },
        pauseTimer() {
            this.timerActive = false;
            clearInterval(this.timer);
        },
        resetTimer() {
            this.pauseTimer();
            this.seconds = 0;
        },
        showLineWay(event) {
            // 获取点击位置相对于容器的偏移量
            const offsetX = event.clientX - event.target.getBoundingClientRect().left;
            this.showLine = true;
            this.linePosition = offsetX;
        },
        currentTime() {
            // 格式化当前时间为指定格式，例如：2024-02-26 15:30:45
            return this.formatDateTime(this.now);
        },
        formatDateTime(date) {
            // 格式化日期时间为 YYYY-MM-DD HH:mm:ss 格式
            const year = date.getFullYear();
            const month = ('0' + (date.getMonth() + 1)).slice(-2);
            const day = ('0' + date.getDate()).slice(-2);
            const hours = ('0' + date.getHours()).slice(-2);
            const minutes = ('0' + date.getMinutes()).slice(-2);
            const seconds = ('0' + date.getSeconds()).slice(-2);
            const milliseconds = ('00' + date.getMilliseconds()).slice(-3); // 获取毫秒部分
            // return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}.${milliseconds}`;
        },
        convertToBinary() {
            var concatenatedBlob = new Blob(this.base64Arry, { type: "audio/wav" });
            this.audio = (window.URL || webkitURL).createObjectURL(concatenatedBlob);
        },
        radioChange() {
            this.destroy();
            // if (this.radioNum > 0) {
            //     this.destroy();
            // }
            // this.radioNum++
        },
        getListAll() {//获取集合数据
            const data = {
                isNet: 1
            }
            getRadioStationList(data).then(response => {
                this.listAll.station = response.rows.filter(item=>item.sdrStatus == '0')
            });


        },
        //销毁全部数据
        async destroy() {
            if(!this.startObj) return; 
            //关闭所有下变频
            for (let i = 0; i < this.popUpData.length; i++) {
                console.log(this.popUpData[i].central + ',' + this.unit.central + "==" + this.popUpData[i].central * this.unit.central);
                await this.postChannelStop(this.popUpData[i].central * this.unit.central);
            }
            this.popUpData = [];
            await this.postFfbStop()//关闭全屏段
            this.radioCode = this.queryParams.radio

        },
        clostJoin() {
           try{
            this.ws.close();
           }catch(e){}
        },
        generateUUIDWithoutHyphens() {
            const uuid = uuidv4();
            return uuid.replace(/-/g, ''); // 使用正则表达式去除连字符
        },
        postSdrSet() {
            // playStop(data).then(response => { });
        },
        sendHeartbeat() {
            const heartbeatMessage = {
                "type": "ffb",
                "central": 6250000,
                "bandwidth": 5000000,
                "resolution_ratio": 0,
                "points": 1024
            };
            sdrSet(data).then(response => { });
            // this.ws.send(JSON.stringify(heartbeatMessage));
        },
        sendFrequencySet() {
            // this.ws.addEventListener('open', () => {
            //     console.log('WebSocket建立连接');
            //     this.heartbeatInterval = setInterval(() => {
            //         this.sendHeartbeat();
            //     }, 5000); // 5秒发送一次心跳
            // });
        },
        join() {
            const self = this;
            const data = {
                cmd: "web-connect",
                data: { id: self.uuid }
                // data: { id: 1003 }
            }
            const jsonData = JSON.stringify(data);
            const encodedData = encodeURIComponent(jsonData);
            const wsuri = this.url + '?' + encodedData;
            console.log('连接socket:',wsuri)
            this.ws = new WebSocket(wsuri);
            this.ws.onopen = function (event) {
                self.text_content = self.text_content + "已经打开连接!" + "\n";
                console.log("连接成功");
            };
            //连接成功
            this.ws.onmessage = function (event) {
                console.log("收到消息:",event)
                // console.log("链接成功");
                // console.log(event);
            };



            self.ws.onclose = function (event) {
                self.text_content = self.text_content + "连接已关闭!" + "\n";
                console.log("连接关闭");
                // 重新连接
                // clearInterval(this.heartbeatInterval);
                self.join();
            };
            this.ws.addEventListener('message', (event) => {
                this.verificationWs(event.data);
            });
        },
        verificationWs(jsonString) {//验证WebSocket发送的信息
            let data;
            // console.log("接收心跳xx");
            try {
                data = JSON.parse(jsonString);
                // console.log("接收心跳11" + jsonString);

            } catch (error) {
                // console.error("无法转为 JSON", error);
                return
            }
            if (data.cmd) {//验证是否带有cmd参数
                if (data.cmd == "sdr-result") {//接收主频率图-开始ffb
                    this.beFrequency = true
                    const sdrData = data.data
                    const sdr = {
                        central: new Decimal(sdrData.central).mul(0.001).toNumber(),
                        need_points: new Decimal(sdrData.bandwidth).mul(0.001).toNumber(),
                        points: sdrData.points,
                        data: sdrData.data,
                        bandwidth: new Decimal(sdrData.bandwidth).mul(0.001).toNumber(),
                    }
                    this.frequencyData = sdr
                } else if (data.cmd == "channel-result") {//接收副频率图-开始下变频
                    // console.log("下变频数据");
                    // console.log(data);
                    const sdrData = data.data
                    const sdr = {
                        central: new Decimal(sdrData.central).mul(0.001).toNumber(),
                        need_points: new Decimal(sdrData.bandwidth).mul(0.001).toNumber(),
                        points: sdrData.points,
                        data: sdrData.data,
                        bandwidth: new Decimal(sdrData.bandwidth).mul(0.1).toNumber() + this.bandwidthAdd,
                        audio: null,
                    }
                    // console.log("下变频数据");
                    // console.log(sdr);
                    this.setPopUpData(sdr)
                    // this.frequencyData = sdr
                } else if (data.cmd == "wave-result") {
                    console.log("接收音频播放");
                    const now = new Date();
                    console.log("当前时间", this.formatDateTime(now));
                    // 收到音频URL
                    const audioUrl = base64PlayUrl(data.data.data)
                    this.getAudioDuration(audioUrl);
                    this.audioUrls.push(audioUrl);
                    // 缓冲并播放音频
                    this.bufferAndPlayAudio(audioUrl);
                } else if (data.cmd == "web-online") {
                    const heartbeatMsg = {
                        cmd: "web-online",
                        data: {
                            type: "ffb",
                            central: "4500000"
                        }
                    };
                    console.log("接收心态xx");
                    const jsonData = JSON.stringify(heartbeatMsg);
                    // this.ws.send(jsonData); // 发送心跳消息
                }

            }


        },
        //获取音频时长
        async getAudioDuration(audioUrl) {
            try {
                // 创建一个新的音频上下文
                const audioContext = new (window.AudioContext || window.webkitAudioContext)();

                // 使用 fetch 方法获取音频文件的 ArrayBuffer
                const response = await fetch(audioUrl);
                console.log("音频数据:",response)
                const audioData = await response.arrayBuffer();
                console.log("buff:",audioData)
                // 解码音频数据
                const decodedData = await audioContext.decodeAudioData(audioData);

                // 获取音频时长（单位：秒）
                this.audioDuration = decodedData.duration.toFixed(3); // 保留三位小数
                console.log("音频时间", this.audioDuration);
                // 关闭音频上下文
                audioContext.close();
            } catch (error) {
                console.error('Error getting audio duration:', error);
            }
        },
        async bufferAndPlayAudio(audioUrl) {
            if (!this.audioContext) {
                this.audioContext = new AudioContext();
            }

            // 下载音频数据
            fetch(audioUrl)
                .then(response => response.arrayBuffer())
                .then(audioData => {
                    // 解码音频数据
                    return this.audioContext.decodeAudioData(audioData);
                })
                .then(decodedData => {
                    // 将解码后的音频数据放入缓冲队列
                    this.audioBufferQueue.push(decodedData);
                    // 检查是否需要开始播放
                    if (!this.bufferTimer) {
                        // 如果定时器不存在，启动一个新的
                        this.bufferTimer = setTimeout(this.playCachedAudio.bind(this), 3000); // 5秒后播放
                    }
                })
                .catch(error => {
                    console.error('Error buffering and playing audio:', error);
                });
        },
        playCachedAudio() {
            if (this.audioBufferQueue.length === 0) return;

            const buffer = this.audioBufferQueue.shift(); // 从缓冲队列中取出一个音频数据

            // 创建音频源
            const source = this.audioContext.createBufferSource();
            source.buffer = buffer;

            // 连接到音频输出
            source.connect(this.audioContext.destination);

            // 播放音频
            source.start();

            // 设置定时器，以便在下一个音频片段结束后播放下一个
            this.bufferTimer = setTimeout(this.playCachedAudio.bind(this), buffer.duration * 1000);
        },
        pauseAudio() {
            // 清除缓冲定时器
            clearTimeout(this.bufferTimer);
            // 停止当前音频源
            if (this.currentBufferSource) {
                this.currentBufferSource.stop();
            }
            this.bufferTimer = null;
            this.audioBufferQueue = [], // 音频数据缓冲队列
                this.bufferTimer = null, // 定时器
                this.audioUrl = '', // 音频URL
                this.audioDuration = null // 音频时长，初始值为null
            this.audioUrl = []
            this.audioContext = null
            this.audioBufferSources = []
            this.currentBufferSource = null

        },

        connectAndPlayAudio() {
            if (this.audioBufferSources.length === 0) return;

            // 移除前一个缓冲的音频源
            if (this.currentBufferSource) {
                this.currentBufferSource.disconnect();
            }

            // 衔接音频数据
            const firstSource = this.audioBufferSources[0];
            this.currentBufferSource = firstSource;
            this.audioBufferSources.shift();

            if (this.audioBufferSources.length > 0) {
                // 缓冲1秒钟
                const nextSource = this.audioBufferSources[0];
                const currentTime = this.audioContext.currentTime;
                nextSource.start(currentTime + 1);
            }

            // 播放音频
            this.currentBufferSource.connect(this.audioContext.destination);
            this.currentBufferSource.start();
        },
        togglePlayback() {
            this.playing = !this.playing;
            if (this.playing) {
                if (!this.currentBufferSource) {
                    // 如果当前没有音频源，尝试播放下一个
                    this.connectAndPlayAudio();
                } else {
                    // 暂停后恢复播放
                    this.currentBufferSource.start(0, this.audioContext.currentTime);
                }
            } else {
                // 暂停播放
                // this.currentBufferSource.stop();
                this.pauseAudio();
            }
        },

        closeDialogPopUp(val) {
            this.postChannelStop(val.central);
        },
        cancelFrequencySet(val) {
            this.frequencySet.open = false
        },
        setNumber(num) {
            this.frequencyNum = (num / 1000).toFixed(3);
        },
        //定时器处理音频
        startTimer() {
            this.timerInterval = setInterval(this.audioProcessing, 3000);
        },
        audioProcessing() {
            // console.log("播放数据音频")
            // console.log(this.base64String)
            this.audio = this.base64String
            // this.audioElement.src = base64PlayUrl(this.base64String);
            // if (this.audioPlay) {//当前为开启状态就播放
            //     this.audioElement.play();
            //     console.log("this.base64String");
            //     console.log(this.base64String);
            //     this.audioElement.addEventListener('ended', this.onAudioEnded);
            // }
        },
        onAudioEnded() {
            // 清空 base64String
            this.base64String = '';
        },
        setPopUpData(val) {
            for (let i = 0; i < this.popUpData.length; i++) {
                if (this.popUpData[i].central == val.central) {
                    this.popUpData[i].frequencyData = val;
                    // num++
                }
            }
        },
        belowAddPopUpData() {//下载下变频数据
            if (!this.beFrequency) {
                return
            }
            this.addPopUpData(this.frequencyNum * this.unit.central);
        },
        addPopUpData(val) {
            // 每次点击按钮，向数组中添加新的组件数据frequencyNum
            // console.log("下变频的数据添加");
            this.postChannelStart(val);//发送下变频
            const data = {
                id: this.generateUniqueId(),
                frequencyData: null,
                central: val,
            }
            console.log(data);
            this.popUpData.push(data);
            // let num = 0;
            // for (let i = 0; this.popUpData.length < 0; i++) {
            //     if (this.popUpData[i].central == val.central) {
            //         this.popUpData[i].frequencyData = val;
            //         num++
            //     }
            // }
            // if (num == 0) {
            // }

            // 动态组件的名称，可以是组件的变量名或字符串
            // this.dynamicComponent = this.generateUniqueId();
        },
        generateUniqueId() {
            const timestamp = new Date().getTime().toString(16); // 时间戳的16进制表示
            const randomPart = Math.random().toString(16).substring(2); // 随机数的16进制表示，去掉0.
            const uniqueId = timestamp + randomPart;
            return uniqueId;
        },
        getParameter() {//获取设置参数
            queryParameter().then(response => {
                // rows
                if (response.code == 200) {
                    this.frequencySet.open = true
                    this.frequencySet.data = response.rows
                    this.frequencySet.data[0].configValue /= 1000 * 1000
                    this.frequencySet.data[1].configValue /= 1000 * 1000
                    console.log(this.frequencySet.data);
                }
            });
        },
        postParameter() {//设置参数
            const data = {
                radioStationCode: this.queryParams.radio,
                // data: this.frequencySet.data
                data: JSON.parse(JSON.stringify(this.frequencySet.data))
            }
            data.data[0].configValue *= 1000 * 1000
            data.data[1].configValue *= 1000 * 1000
            console.log("修改:",data)
            editParameter(data).then(response => {
                this.frequencySet.open = false
                this.$modal.msgSuccess("修改成功");
            });
        },
        saveData() {
            console.log("存了");
            console.log(this.radioCode);
            this.radioCode = this.queryParams.radio
            localStorage.setItem('frequencyRadioCode', this.radioCode);
        },
        // getData() {
        //     this.radioCode = localStorage.getItem('frequencyRadioCode') || null;
        //     this.queryParams.radio = this.radioCode
        //     console.log("取了");
        //     console.log(this.queryParams.radio);
        // },

        async postFfbStart() {//ffb开始
            // this.join()
            // let central = 4500
            // let bandwidth = 2000
            this.saveData()
            await queryParameter().then(response => {
                // rows
                if (response.code == 200) {
                    this.bandwidth = response.rows[0].configValue/1000/1000
                    this.central = response.rows[1].configValue/1000/1000
                    this.frequencyNum = this.central
                    // return
                    const data = {
                        radioStationCode: this.queryParams.radio,
                        id: this.uuid,
                        data: {
                            "type": "channel",
                            "central": this.central * this.unit.central  * this.unit.central,
                            "bandwidth": this.bandwidth * this.unit.bandwidth,
                            "resolution_ratio": 3000,
                            "sample_frequence": 2000000,
                            "points": 1024,
                            "modem": "c0",
                            "mode": "ssb"
                        }
                    }

                    ffbStart(data).then(response => {//发送全频道
                        if (response.code == 200) {
                            this.resetTimer()
                            this.startTimers()
                            this.popUpData = []
                            this.beFrequency = true
                            this.addPopUpData(this.central* this.unit.central);
                            console.log("开启了：",data)
                            this.startObj = data;
                        }
                    });
                }
            });

        },
        async postFfbStop() {//ffb停止
            if(!this.startObj) return; 
            const data = {
                radioStationCode: this.startObj.radioStationCode,
                id: this.startObj.id,
                data: {
                    "type": "ffb",
                    "central": this.central * this.unit.central
                }
            }
            console.log("停止：",data)
            for (let i = 0; this.popUpData.length > i; i++) {
                await this.postChannelStop(this.popUpData[i].central)
            }
            await ffbStop(data).then(response => {
                this.startObj = null;
                if (response.code == 200) {
                    this.beFrequency = false
                    this.pauseTimer()
                    if (this.popUpData.length > 0) {
                        this.popUpData = [
                            this.popUpData[0]
                        ]
                    } else {
                        this.popUpData = []
                    }
                    this.$modal.msgSuccess("已停止");
                }
            });
        },
        postChannelStart(val) {//下变频开始
            if (this.beFrequency == false) {
                return
            }
            const data = {
                radioStationCode: this.queryParams.radio,
                id: this.uuid,
                data: {
                    "type": "channel",
                    "central": val * this.unit.central,
                    "bandwidth": 12000,
                    "resolution_ratio": 3000,
                    "sample_frequence": 12000,
                    "points": 256,
                    "modem": "c0",
                    "mode": "ssb"
                }
            }
            console.log("开始下变频")
            channelStart(data).then(response => {
                if (response.code == 200) {
                    this.$modal.msgSuccess("下变频启动成功");
                }
            });
        },
        async postChannelStop(val) {//下变频结束
            const data = {
                radioStationCode: this.startObj.radioStationCode,
                id: this.startObj.id,
                data: {
                    "type": "channel",
                    "central": val * this.unit.central
                }
            }
            await channelStop(data).then(response => {
                if (response.code == 200) {
                    // this.$modal.msgSuccess("发送成功");
                }
            });
        },
        async playStart(val) {
            // this.togglePlayback()

            if (this.playCentral == val.central) {//如果和旧的中心频率相同就暂停
                // console.log("暂停", val * 1000);
                this.pauseAudio();
                this.postPlayStop(val.central);
                this.playCentral = null
                this.audioBufferQueue = []
            } else if (this.playCentral == null || this.playCentral != val.central) {//为null或者不相同就是开启
                //开启需要将新值赋给旧值
                this.playCentral = val.central
                // if(!this.playCentral){
                //     await this.postPlayStop(val*100);
                // }
                await this.postPlayStart(val)
                if (!this.currentBufferSource) {
                    // 如果当前没有音频源，尝试播放下一个
                    this.connectAndPlayAudio();
                } else {
                    // 暂停后恢复播放
                    this.currentBufferSource.start(0, this.audioContext.currentTime);
                }
                // console.log("播放", val * 1000);
            }
        },
        async go(val) {
            // console.log(val);
            // const data = {
            //     id: this.generateUniqueId(),
            //     frequencyData: null,
            //     central: 4500,
            // }
            // this.popUpData.push(data);
            // return
            if (this.beFrequency == false) {
                return
            }
            await this.postChannelStartGo(val)
        },
        async postChannelStartGo(val) {//下变频开始播放go按钮
            const data = {
                radioStationCode: this.radioCode,
                id: this.uuid,
                data: {
                    "central": val.central * this.unit.central,
                    bandwidth: val.bandwidth * this.unit.bandwidthGo,
                    mode: val.mode,
                    modem: val.modem,
                    "type": "channel",
                    "resolution_ratio": 3000,
                    "sample_frequence": 12000,
                    "points": 256,
                }
            }
            // return
            await channelStart(data).then(response => {
                if (response.code == 200) {
                    this.$modal.msgSuccess("发送成功");
                     for (let i = 0; i < this.popUpData.length; i++) {
                        if (this.popUpData[i].id === val.id) {
                            this.postPlayStop(this.popUpData[i].central)
                            this.popUpData[i].central =  val.central;
                            break; // 找到后跳出循环
                        }
                    }
                    // const data = {
                    //     id: this.generateUniqueId(),
                    //     frequencyData: null,
                    //     central: val.central,
                    // }
                    // this.popUpData.push(data);
                }
            });
        },
        async postPlayStart(val) {//下变频开始播放
            //
            // console.log(val)
            // return
            const data = {
                radioStationCode: this.radioCode,
                id: this.uuid,

                data: {
                    bandwidth: val.need_points * 1000,
                    // "central": 4500000
                    "central": val.central * this.unit.central
                }
            }
            await playStart(data).then(response => {
                if (response.code == 200) {
                    this.$modal.msgSuccess("发送成功");
                    this.audioPlay = true
                }
            });
        },
        async postPlayStop(val) {//下变频结束播放停止
            const data = {
                id: this.uuid,
                radioStationCode: this.radioCode,
                data: {
                    // "central": 4500000
                    "central": val * this.unit.central
                }

            }
            this.audioPlay = false
            this.audioElement.pause();
            await playStop(data).then(response => {
                if (response.code == 200) {
                    // this.$modal.msgSuccess("发送成功");
                }
            });
        },
        postRecordStart(val) {//下变频开始记录
            const data = {
                radioStationCode: this.radioCode,
                id: this.uuid,
                data: {
                    "central": val * this.unit.central
                }

            }
            recordStart(data).then(response => {
                if (response.code == 200) {
                    this.$modal.msgSuccess("发送成功");
                }
            });
        },
        postRecordStop(val) {//下变频结束记录
            const data = {
                radioStationCode: this.radioCode,
                id: this.uuid,
                data: {
                    "central": val * this.unit.central
                }

            }
            recordStop(data).then(response => {
                if (response.code == 200) {
                    this.$modal.msgSuccess("发送成功");
                }
            });
        },
    }
};
</script>


<style rel="stylesheet/scss" lang="scss" scoped>
.frequency-message-minor {
    .frequency-headline {
        background: linear-gradient(to right, #313B53, #272F43);
        height: 45px;
        line-height: 52px;
        padding-left: 10px;
        border-radius: 15px 15px 0 0;
        color: #9A9DAA;
        font-weight: 700;
    }

}

.fry-box {
    background: #171D2C;
    width: 100%;
    padding: 10px;
    border-radius: 50px;
}

.overall-set {
    cursor: pointer;
    margin-right: 30px;
    margin-left: 20px;

    img {
        width: 30px;
        margin-right: 5px;
    }

    color: #2CA6E0;
    font-size: 16px;
}

.zt-sdr {
    margin-left: 30px;

    img {
        width: 25px;
        margin-right: 5px;
    }

    .sdr-dian {
        font-size: 30px;
    }

    .sdr-text {
        margin-left: 5px;
        font-size: 16px;
    }

    color: #74C8CE;
}

.zt-data {
    // margin-left: 30px;
    margin-left: auto;
    margin-right: 20px;

    img {
        width: 20px;
        margin-right: 5px;
    }

    color: #fff;
}


.container {
    position: relative;
    //   height: 100px;
    //   width: 200px;
    //   background-color: #f0f0f0;
}

.line {
    position: absolute;
    left: 50%;
    top: 10%;
    transform: translateX(-50%);
    width: 2px;
    height: 62%;
    background-color: #FFE355;
    pointer-events: none;
    /* 防止线条遮挡点击事件 */
}

.h-num-input {
    appearance: none;
    border: none;
    background: none;
    margin: 0;
    padding: 0;
    outline: none;
    font: inherit;
    text-align: inherit;
    color: inherit;
    width: 65px;
    margin-left: 10px;

}

.h-num-input[type=number]::-webkit-inner-spin-button,
.h-num-input[type=number]::-webkit-outer-spin-button {
    -webkit-appearance: none;
    margin: 0;
}
</style>